#include "TCanvas.h"
#include "TF1.h"
#include "TFile.h"
#include "TH1D.h"
#include "TMinuit.h"
#include "TDirectory.h"

#include "FitTRDdEdx.h"

//how to compile and execute
/*
g++ dofit.C  -O3 -Wall -I$ROOTSYS/include $(root-config --libs) -lMinuit -L./ -lFitTRDdEdx -o dofit
export LD_LIBRARY_PATH=$(pwd):$LD_LIBRARY_PATH

./dofit dEdx_2004_inv8.root h201
 */

void dofit(TH1D *hh)
{
  TCanvas *cc=new TCanvas("cc");
  gPad->SetLogy();
  gPad->SetGrid();

  hh->Draw();
  const Double_t hmax = hh->GetBinContent(hh->GetMaximumBin());
  Double_t par[10]={hh->Integral("width"), hh->GetBinCenter(hh->GetMaximumBin()), hh->GetRMS()}, err[10], chi[10];
  FitTRDdEdx::FFunc func = 0x0;
  Double_t npar = 0;

  //fit 0
  func = FitTRDdEdx::ALandau;
  npar = 3;
  FitTRDdEdx::ChisquareFit(hh, func, npar, par, err, chi, hmax/10);
  TH1D *f0 = FitTRDdEdx::DrawFunc(hh,func,par,"hist", kBlue);
  f0->SetName("f0");

  //fit 1
  func = FitTRDdEdx::ALG;
  npar = 4;
  par[3] = par[2];
  FitTRDdEdx::ChisquareFit(hh, func, npar, par, err, chi, hmax/100);
  TH1D *f1 = FitTRDdEdx::DrawFunc(hh,func,par,"hist", kRed);
  f1->SetName("f1");

  //fit 2
  func = FitTRDdEdx::DimlessALGE;
  npar = 5;
  par[2] /= par[1];
  par[3] /= par[1];
  par[4] = 0;
  FitTRDdEdx::ChisquareFit(hh, func, npar, par, err, chi);
  TH1D *f2 = FitTRDdEdx::DrawFunc(hh,func,par,"hist", kBlack);
  f2->SetName("f2");
 
  TFile *fout=new TFile("fout.root","recreate");
  cc->Write();
  f0->Write();
  f1->Write();
  f2->Write();
  fout->Save();
  fout->Close();
}

int main(int argc, char * argv[])
{
  TFile::Open(argv[1]);
  TH1D *hh=(TH1D*)gDirectory->Get(argv[2]);
  if(!hh){
    return 1;
  }

  dofit(hh);
  return 0;
}
